const app = require('j7/app');
const utils = require('j7/utils');
const bcutils = require('j7/bcutils');
const bcconst = require('common/bcconst');
const metaFactory = require('../metadata/factory');
const serviceFactory = require('../services/factory');

async function approveErc20(session) {
  try {
    const accountAddress = bcutils.toNormalAddress(session.request('account_address'));
    const netId = session.request('net_id');
    const spender = bcutils.toNormalAddress(session.request('spender'));
    const value = session.request('value');
    const currencyName = session.request('currency_name');
    const bc = serviceFactory.create('BlockChain');
    {
      const ret = await bc.init(netId);
      if (!ret) {
        session.rspErr(500, 'net_id error');
        return;
      }
    }
    {
      if (!bc.isValidAddress(accountAddress)) {
        session.rspErr(500, 'account_address error');
        return;
      }
    }
    {
      if (!bc.isValidAddress(spender)) {
        session.rspErr(500, 'spender error');
        return;
      }
    }
    const contractMeta = bc.getContractByName(currencyName);
    if (!contractMeta) {
      session.rspErr(500, 'currency meta not found');
      return;
    }
    console.log(contractMeta);
    if (contractMeta['type'] != 'erc20') {
      session.rspErr(500, 'currency meta type error');
      return;
    }

    const instance = bc.getInstanceByName(currencyName);
    if (!instance) {
        session.rspErr(500, 'currency error');
        return;
    }
    let data = instance.methods.approve
    (
      spender,
      value).encodeABI();

    session.rspData({
      'trans_id' : '',
      'trans_req': {
        'to': contractMeta['address'],
        'data': data
      }
    });
  } catch (e) {
    session.rspErr(1, 1);
    utils.safeDumpErrStack(e);
    console.log(e);
  }
}

function init() {
  app.registerHandler('BcService', 'approveErc20', approveErc20);
}

exports.init = init;
